package com.hs.srm.admin.modules.requisition.controller;

import com.hs.srm.admin.modules.orders.dao.ScmPoItemDao;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestHeaderEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestHeaderSapService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemSapService;
import com.sap.conn.jco.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * 生产性申请单定时任务
 *
 * @author socik
 * @date 2019/5/5 10:24
 */
@Component("proPurchRequetSapTask")
public class ProPurchRequetSapTask {

    Logger logger = LoggerFactory.getLogger(ProPurchRequetSapTask.class);

    @Autowired
    private ProPurchRequestHeaderSapService proPurchRequestHeaderSapServiceImpl;

    @Autowired
    private ProPurchRequestItemSapService ProPurchRequestItemSapServiceImpl;

    @Autowired
    private NproPurchRequestHeaderService nproPurchRequestHeaderService;

    @Autowired
    private NproPurchRequestItemService nproPurchRequestItemService;

    @Autowired
    private ScmPoItemService scmPoItemService;

    @Autowired
    private ScmPoItemDao scmPoItemDao;

    /**
     * @Description insertHeaderAndItem
     * @Param []
     * @Return void
     * @Author socik
     * @Date 2019/5/5 10:52
     */
    @Transactional(rollbackFor = Exception.class)
    public void insertHeaderAndItem() {
        //生产性请求头、行项目entity
        ProPurchRequestHeaderEntity headerEntity = new ProPurchRequestHeaderEntity();
        ProPurchRequestItemEntity itemEntity = new ProPurchRequestItemEntity();
        //非生产性请求头、行项目entity
        NproPurchRequestHeaderEntity nproHeaderEntity = new NproPurchRequestHeaderEntity();
        NproPurchRequestItemEntity nproItemEntity = new NproPurchRequestItemEntity();

        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList list = null;
        //调用SAP接口
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZPUR_REQ_SAP_TO_SRM");
            list = function.getTableParameterList();
        } catch (JCoException e) {
            e.printStackTrace();
        }
        JCoTable jCoFieldsTable = list.getTable("R_CRDAT");
        jCoFieldsTable.appendRow();
        jCoFieldsTable.setValue("SIGN", "I");
        jCoFieldsTable.setValue("OPTION", "BT");
        jCoFieldsTable.setValue("LOW", "00000000");
        jCoFieldsTable.setValue("HIGH", "99999999");
        JCoTable jCoTable = list.getTable("R_WERKS");
        jCoTable.appendRow();
        jCoTable.setValue("SIGN", "I");
        jCoTable.setValue("OPTION", "BT");
        //low heigh,从SAP获取申请单工厂条件
        jCoTable.setValue("LOW", "1000");
        jCoTable.setValue("HIGH", "8888");
        try {
            function.execute(destination);
        } catch (JCoException e) {
            e.printStackTrace();
        }
        JCoTable returnTable = list.getTable("OUT_TAB");
        JCoTable returnItem = list.getTable("OUT_EBAN");
        //采购订单表头添加数据
        if (returnTable.getNumRows() > 0 && returnItem.getNumRows() > 0) {
            for (int j = 0; j < returnItem.getNumRows(); j++) {
                //请求类型标志：true，生产性；false，非生产性
                boolean typeFlag = true;
                returnItem.setRow(j);
                if (returnTable.getValue("BANFN").equals(returnItem.getValue("BANFN"))) {
                    itemEntity.setMaterialCode(((String) returnItem.getValue("MATNR")).replaceAll("^(0+)", ""));
                    //物料号为空，表示该申请是非生产性的
                    if (StringUtils.isBlank(itemEntity.getMaterialCode())) {
                        typeFlag = false;
                    }
                    itemEntity.setMaterialDesc((String) returnItem.getValue("TXZ01"));
                    itemEntity.setPurchRequestCode((String) returnItem.getValue("BANFN"));
                    itemEntity.setPurchRequestItemCode((String) returnItem.getValue("BNFPO"));
                    itemEntity.setPrCategory((String) returnItem.getValue("BSTYP"));
                    itemEntity.setPrType((String) returnItem.getValue("BSART"));
                    itemEntity.setApproveFlag((String) returnItem.getValue("FRGKZ"));
                    itemEntity.setPurchGroup((String) returnItem.getValue("EKGRP"));
                    itemEntity.setPurchOrg((String) returnItem.getValue("EKORG"));
                    itemEntity.setApplier((String) returnItem.getValue("AFNAM"));
                    itemEntity.setFactory((String) returnItem.getValue("WERKS"));
                    itemEntity.setStorageLocation((String) returnItem.getValue("LGORT"));
                    itemEntity.setMaterialGroup((String) returnItem.getValue("MATKL"));
                    //计量单位 G 转成 KG ，采购数量/1000
                    String measureUnit = (String) returnItem.getValue("MEINS");
                    BigDecimal applyQty = new BigDecimal(returnItem.getValue("MENGE").toString());
                    if (measureUnit.equals("G")) {
                        measureUnit = "KG";
                        applyQty = applyQty.movePointLeft(3);
                    }
                    itemEntity.setMeasureUnit(measureUnit);
                    itemEntity.setApplyQty(applyQty);
                    itemEntity.setDeliveryDate(((Date) returnItem.getValue("LFDAT")));
                    itemEntity.setDeliveryDateType((String) returnItem.getValue("LPEIN"));
                    Object object = returnItem.getValue("PREIS");
                    itemEntity.setPurchRequestPrice(new BigDecimal(object.toString()));
                    itemEntity.setMrpOwner((String) returnItem.getValue("DISPO"));
                    itemEntity.setDesiredVendor((String) returnItem.getValue("LIFNR"));
                    itemEntity.setFixedVendor((String) returnItem.getValue("FLIEF"));
                    itemEntity.setAssignedSupplySource((String) returnItem.getValue("ZUGBA"));
                    itemEntity.setRemark((String) returnItem.getValue("ZTEXT"));
                    //默认是-2
                    //itemEntity.setGoodsStatus(-2);
                    itemEntity.setMrpOwner((String) returnItem.getValue("DISPO"));
                    itemEntity.setDesiredVendor((String) returnItem.getValue("LIFNR"));
                    itemEntity.setFixedVendor((String) returnItem.getValue("FLIEF"));
                    itemEntity.setAssignedSupplySource((String) returnItem.getValue("ZUGBA"));
                    itemEntity.setCreationDate((Date) returnTable.getValue("CRDAT"));
                    itemEntity.setSrmReceiveDate(new Date());
                    headerEntity.setPurchRequestType("ZBZ");
                    headerEntity.setPurchRequestCode((String) returnTable.getValue("BANFN"));
                    headerEntity.setCreatedBy((String) returnTable.getValue("CRNAM"));
                    headerEntity.setCreationDate((Date) returnTable.getValue("CRDAT"));
                    headerEntity.setLastUpdatedBy((String) returnTable.getValue("CRNAM"));
                    headerEntity.setLastUpdateDate((Date) returnTable.getValue("CHDAT"));
                    headerEntity.setGuid32((String) returnTable.getValue("GUID32"));
                    //默认是-2
                    //headerEntity.setGoodsStatus(-2);
                    //生产性的申请单
                    if (typeFlag) {
                        ProPurchRequestHeaderEntity header = proPurchRequestHeaderSapServiceImpl.selectProHeader((String) returnTable.getValue("BANFN"));
                        ProPurchRequestItemEntity item = ProPurchRequestItemSapServiceImpl.selectProItem((String) returnItem.getValue("BANFN"), "" + returnItem.getValue("BNFPO"));
                        //先判断采购申请头是不是为空
                        if (header == null) {
                            proPurchRequestHeaderSapServiceImpl.insertProHeader(headerEntity);
                        } else {
                            headerEntity.setPkId(header.getPkId());
                            proPurchRequestHeaderSapServiceImpl.updateById(headerEntity);
                        }
                        //判断行项目是不是为空
                        if (item == null) {
                            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                            itemEntity.setPkId(uuid);
                            ProPurchRequestItemSapServiceImpl.insertProItem(itemEntity);
                        } else {
                            //申请数量变更或需求日期变更
                            if (!item.getApplyQty().equals(itemEntity.getApplyQty()) || !item.getDeliveryDate().equals(itemEntity.getDeliveryDate())) {
                                //仓库在SAP修改请购单，已生成但未同步SAP的订单退掉
                                //通过采购申请编号purchRequestCode、行项目号purchRequestItemCode找出所有订单id
                                List<ScmPoItemEntity> itemList = scmPoItemDao.getItemListByPurchRequest(item.getPurchRequestCode(), item.getPurchRequestItemCode());
                                List<String> li = itemList.stream().map(ScmPoItemEntity::getPoItemId).distinct().collect(Collectors.toList());
                                if (li.size() > 0) {
                                    String[] itemIds = new String[li.size()];
                                    li.toArray(itemIds);
                                    scmPoItemService.deleteOrders("PRO", itemIds);
                                }
                            }
                            itemEntity.setPkId(item.getPkId());
                            ProPurchRequestItemSapServiceImpl.updateById(itemEntity);
                        }
                    } else {//非生产性
                        //将生产性头数据和行项目数据复制到非生产性的entity中
                        BeanUtils.copyProperties(headerEntity, nproHeaderEntity);
                        BeanUtils.copyProperties(itemEntity, nproItemEntity);

                        //采购申请类型
                        nproHeaderEntity.setPurchRequestType("NPRO");
                        //SRM收到申请单日期
                        nproHeaderEntity.setSrmReceiveDate(new Date());
                        //非生产性需求日期
                        nproItemEntity.setRequestDate(nproItemEntity.getDeliveryDate());
                        //科目类别
                        nproItemEntity.setSubjectCategory((String) returnItem.getValue("KNTTP"));

                        //采购申请编码加上PR前缀，表示非生产性
                        nproHeaderEntity.setPurchRequestCode("PR" + nproHeaderEntity.getPurchRequestCode().substring(2));
                        nproItemEntity.setPurchRequestCode("PR" + nproItemEntity.getPurchRequestCode().substring(2));

                        NproPurchRequestHeaderEntity header = nproPurchRequestHeaderService.selectNproHeader(nproItemEntity.getPurchRequestCode());
                        NproPurchRequestItemEntity item = nproPurchRequestItemService.selectNproItem(nproItemEntity.getPurchRequestCode(), nproItemEntity.getPurchRequestItemCode());
                        //先判断采购申请头是不是为空
                        if (header == null) {
                            nproPurchRequestHeaderService.insert(nproHeaderEntity);
                        } else {
                            nproHeaderEntity.setPkId(header.getPkId());
                            nproPurchRequestHeaderService.updateById(nproHeaderEntity);
                        }
                        //判断行项目是不是为空
                        if (item == null) {
                            nproPurchRequestItemService.insert(nproItemEntity);
                        } else {
                            itemEntity.setPkId(item.getPkId());
                            nproPurchRequestItemService.updateById(nproItemEntity);
                        }
                    }
                    try {
                        function = destination.getRepository().getFunction("ZPUR_REQ_SRM_TO_SAP");
                        list = function.getTableParameterList();
                    } catch (JCoException e) {
                        e.printStackTrace();
                    }
                    JCoTable intab = list.getTable("IN_TAB");
                    intab.appendRow();
                    intab.setValue("GUID32", headerEntity.getGuid32());
                    try {
                        function.execute(destination);
                    } catch (JCoException e) {
                        e.printStackTrace();
                    }
                    logger.info("采购申请同步成功!!采购申请号为" + headerEntity.getPurchRequestCode());
                }
            }
        } else {
            logger.debug("SAP无更新数据!");
        }
    }
}
